package com.tubeonfire.controller.admin;

import java.io.IOException;
import java.util.Calendar;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.tubeonfire.entity.Channel;
import com.tubeonfire.model.admin.ChannelModel;
import com.tubeonfire.util.ChannelValidate;

@SuppressWarnings("serial")
public class EditChannelServlet extends HttpServlet {

	private static final Logger log = Logger.getLogger(EditChannelServlet.class
			.getName());

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		try {
			HttpSession session = req.getSession();
			String id = req.getParameter("id");
			Channel obj = ChannelModel.getById(id);
			if (obj != null) {
				session.setAttribute("obj", obj);
				req.getRequestDispatcher("/admin/form_channel.jsp").forward(
						req, resp);
			} else {
				session.setAttribute("error",
						"Channel's not exists or has been deleted !");
				resp.sendRedirect("/admin/channel/list");
			}
		} catch (Exception e) {
			log.warning(e.toString());
			e.printStackTrace();
			resp.sendError(4004,
					"We are sorry for the inconvenience ! Please try again later !");
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			HttpSession session = req.getSession();
			String id = req.getParameter("id");
			Channel obj = ChannelModel.getById(id);
			if (obj != null) {
				ChannelValidate.checkForm(req, obj);
				obj.setUpdated(Calendar.getInstance().getTime());
				ChannelModel.insert(obj);
				session.setAttribute("success", "Action success !");
				resp.sendRedirect("/admin/channel/edit?id=" + id);
			} else {
				session.setAttribute("error",
						"Channel's not exists or has been deleted !");
				resp.sendRedirect("/admin/channel/list");
			}
		} catch (Exception e) {
			log.warning(e.toString());
			e.printStackTrace();
			resp.sendError(4004,
					"We are sorry for the inconvenience ! Please try again later !");
		}
	}
}
